package com.lb.bs.client.processor.handle.dynamics;

import com.lb.bs.client.annotation.ProcessorMark;
import com.lb.bs.client.annotation.SingletonMark;
import com.lb.bs.client.factory.SingletonFactory;
import com.lb.bs.client.processor.ProcessorHandleService;
import com.lb.bs.client.processor.ProcessorService;
import com.lb.bs.client.processor.beans.ProcessorDynamicBean;
import com.lb.bs.client.processor.beans.ProcessorDynamicHandlerBean;
import com.lb.bs.client.processor.enums.KeyType;
import com.lb.bs.client.processor.enums.ProcessorType;
import com.lb.bs.client.processor.handle.dynamics.create.CreateProcessorHandle;
import com.lb.bs.client.processor.handle.dynamics.create.GrayCreateIPKeyProcessorHandle;
import com.lb.bs.client.processor.handle.dynamics.create.GrayCreateItemKeyProcessorHandle;
import com.lb.bs.client.util.GrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2019-12-02 13:58
 * description:
 */
@SingletonMark
@ProcessorMark(type = ProcessorType.CREATE)
public class DynamicCreateProcessor implements ProcessorService<ProcessorDynamicBean> {
    private static final Logger logger = LoggerFactory.getLogger(DynamicCreateProcessor.class);

    private static final ProcessorHandleService<ProcessorDynamicHandlerBean> createHandle = SingletonFactory.getInstance(CreateProcessorHandle.class);

    private static final ProcessorHandleService<ProcessorDynamicHandlerBean> grayIpHandle = SingletonFactory.getInstance(GrayCreateIPKeyProcessorHandle.class);

    private static final ProcessorHandleService<ProcessorDynamicHandlerBean> grayItemHandle = SingletonFactory.getInstance(GrayCreateItemKeyProcessorHandle.class);


    private static final Map<KeyType, ProcessorHandleService> map = new HashMap<>();

    static {
        map.put(KeyType.ITEM_KEY, createHandle);
        map.put(KeyType.GRAY_IP_KEY, grayIpHandle);
        map.put(KeyType.GRAY_ITEM_KEY, grayItemHandle);
    }


    @Override
    public void process(ProcessorDynamicBean dynamicBean) {
        String zkKey = dynamicBean.getKey();
        logger.info("DynamicCreateProcessor.class, key:" + zkKey);
        String data = dynamicBean.getData();
        //数据为空则不进行更新
        if (data == null) {
            return;
        }

        ProcessorDynamicBean.Builder builder = ProcessorDynamicBean.builder().key(dynamicBean.getKey()).data(dynamicBean.getData());
        ProcessorDynamicHandlerBean handlerBean = new ProcessorDynamicHandlerBean(builder);


        KeyType keyType = GrayUtil.getKeyType(zkKey);

        ProcessorHandleService handleService = map.get(keyType);

        handleService.handleProcess(handlerBean);

    }
}
